package com.ruoyi.common.utils.pdf;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.io.File;

@Slf4j
public class FileUtil {

    public static String getFileName(String path, String name, String suffix) {
        checkPathExist(path);
        String filePath = path +  name + "." + suffix;
        return filePath;
    }

    public static boolean checkPathExist(String path) {
        if (StringUtils.isBlank(path)) {
            return false;
        }
        File directory = new File(path);
        if (!directory.exists()) {
            log.info("----------------mkdir---------");
            directory.mkdirs();
        }
        return true;
    }

    // 作业导出目录，以作业票ID区分
    public static String getZyExportDir(String exportDir, String id) {
        String zyExportPath = exportDir + id;
        File directory = new File(zyExportPath);
        if (!directory.exists()) {
            log.info("----------------mkdir---------");
            directory.mkdirs();
        }
        return zyExportPath;
    }

    // 作业导出目录，以作业票ID区分
    public static String getZySaveFilePath(String path, String name, String id, long time, String suffix) {
        String filePath = path +  name + "_" + id + "_" + time + "." + suffix;
        return filePath;
    }

    public static String getFileNameUnSuffix(String filePath) {
        if (StringUtils.isBlank(filePath)) {
            return System.currentTimeMillis() + "";
        }
        String fileName = filePath.substring(0, filePath.lastIndexOf("."));
        return fileName;
    }

    public static String getFileNameSuffix(String filePath) {
        if (StringUtils.isBlank(filePath)) {
            return System.currentTimeMillis() + "";
        }

        String fileName = filePath.substring(filePath.lastIndexOf(File.separator) + 1);
        return fileName;
    }

    // 删除文件
    public static void delFileByPath(String directoryPath) {
        File directory = new File(directoryPath);
        if (!directory.exists()) {
            return;
        }
        // 获取目录下所有文件
        File[] files = directory.listFiles();

        if (files != null) {
            for (File file : files) {
                //if (file.isFile() && file.getName().endsWith(".pdf")) {
                if (file.isFile()) {
                    // 删除文件
                    if (file.delete()) {
                        log.info(file.getName() + " is deleted!");
                    } else {
                        log.info("Failed to delete " + file.getName());
                    }
                }
            }
        }
    }
}
